region.lag <- function(period, countrycode, region, data, yvar) {
	vector <- unique(cbind(region, countrycode))
	reg.row <- matrix(vector[,1], nrow = length(vector[,2]), ncol = length(vector[,2]), byrow = FALSE, dimnames = list(vector[,2], vector[,2]) )

	reg.col <- matrix(vector[,1], nrow = length(vector[,2]), ncol = length(vector[,2]), byrow = TRUE, dimnames = list(vector[,2], vector[,2]) )

	region.matrix <- matrix(NA, length(vector[,2]), ncol = length(vector[,2]), dimnames = list(vector[,2], vector[,2]) )
	for (c in vector[,2]){
		region.matrix[c,] <- ifelse(reg.row[c,]==reg.col[c,],  region.matrix[c,]  <-  1, region.matrix[c,] <- 0)
	}	
	W  <- region.matrix
	diag(W) <- 0
	W[is.na(W)] <- 0
	# row-standardize the "www" matrix. we need this later.
	n <- nrow(W)
	for(a in 1:n){
		ifelse(sum(W[a,])==0, W[a,]<-0,	W[a,] <- W[a,]/sum(W[a,]))
		}	

	Wy <- as.vector(rep(NA, nrow(data)))
	for (i in period){
		# the Y variable
		y.year  <- data[data$year==i, yvar]
		y.noNA  <- ifelse(is.na(y.year), 0, y.year)
		Wy      <- ifelse(data$year==i, W%*%y.noNA, Wy)		   
		}
	Wy <- ifelse(Wy==0, NA, Wy)	
	}